﻿using System;
using System.Net;
using System.IO;
using System.Text;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Web;
using System.Collections.Generic;
using Newtonsoft.Json;
using AccompanyCabinet.Model;
using System.Configuration;

namespace AccompanyCabinet.Helper
{
    public class HttpHelper
    {

        public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            //直接确认，否则打不开    
            return true;
        }

        public static MJson Post(Dictionary<string, string> parameters, string url, int timeout)
        {
            GC.Collect();//垃圾回收，回收没有正常关闭的http连接
            string result = "";//返回结果
            HttpWebRequest request = null;
            HttpWebResponse response = null;
            try
            {
                /***************************************************************
                * 下面设置HttpWebRequest的相关属性
                * ************************************************************/
                string allurl = ConfigurationManager.AppSettings["RequestURL"].ToString();
                ServicePointManager.DefaultConnectionLimit = 200;
                request = (HttpWebRequest)WebRequest.Create(allurl + url);
                request.ProtocolVersion = HttpVersion.Version10;
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.Timeout = timeout * 1000;
                //如果需要POST数据     
                if (!(parameters == null || parameters.Count == 0))
                {
                    StringBuilder buffer = new StringBuilder();
                    int i = 0;
                    foreach (string key in parameters.Keys)
                    {
                        if (i > 0)
                        {
                            buffer.AppendFormat("&{0}={1}", key, parameters[key]);
                        }
                        else
                        {
                            buffer.AppendFormat("{0}={1}", key, parameters[key]);
                        }
                        i++;
                    }
                    byte[] data = Encoding.UTF8.GetBytes(buffer.ToString());
                    using (Stream stream = request.GetRequestStream())
                    {
                        stream.Write(data, 0, data.Length);
                        stream.Close();
                    }
                }
                //获取服务端返回
                 response = (HttpWebResponse)request.GetResponse();
                StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                result = sr.ReadToEnd().Trim();
                MJson json = new MJson();
                json.Message = result;
                json.status = response.StatusCode.ToString().ToUpper();
                sr.Close();
                return json;
            }
            catch (System.Threading.ThreadAbortException e)
            {
                LogHelper.WriteLog("HttpService Thread - caught ThreadAbortException - resetting." + e.ToString());
                System.Threading.Thread.ResetAbort();
            }
            catch (WebException e)
            {
                var x = e.Response as HttpWebResponse;
                StreamReader sr = new StreamReader(x.GetResponseStream(), Encoding.UTF8);
                result = sr.ReadToEnd().Trim();
                sr.Close();
                sr.Dispose();
                MJson message = JsonConvert.DeserializeObject<MJson>(result);
                message.status = x.StatusCode.ToString();
                return message;
                //LogHelper.WriteLog("HttpService Thread - caught ThreadAbortException - resetting." + e.ToString());
                //throw new Exception(e.ToString());
            }
            catch (Exception e)
            {
                LogHelper.WriteLog("HttpService", e);
                throw new Exception(e.ToString());
            }
            finally
            {
                //关闭连接和流
                if (response != null)
                {
                    response.Close();
                }
                if (request != null)
                {
                    request.Abort();
                }
            }
            return new MJson { Message = result };
        }


        public static MJson PostObj(Dictionary<string, Object> parameters, string url, int timeout)
        {
            GC.Collect();//垃圾回收，回收没有正常关闭的http连接
            string result = "";//返回结果
            HttpWebRequest request = null;
            HttpWebResponse response = null;
            try
            {
                /***************************************************************
                * 下面设置HttpWebRequest的相关属性
                * ************************************************************/
                string allurl = ConfigurationManager.AppSettings["RequestURL"].ToString();
                ServicePointManager.DefaultConnectionLimit = 200;
                request = (HttpWebRequest)WebRequest.Create(allurl + url);
                request.ProtocolVersion = HttpVersion.Version10;
                request.Method = "POST";
                //request.ContentType = "application/x-www-form-urlencoded";
                request.ContentType = "text/xml";
                request.Timeout = timeout * 10000;
                //如果需要POST数据     
                if (!(parameters == null || parameters.Count == 0))
                {
                    StringBuilder buffer = new StringBuilder();
                    int i = 0;
                    foreach (string key in parameters.Keys)
                    {
                        if (i > 0)
                        {
                            buffer.AppendFormat("&{0}={1}", key, parameters[key]);
                        }
                        else
                        {
                            buffer.AppendFormat("{0}={1}", key, parameters[key]);
                        }
                        i++;
                    }
                    byte[] data = Encoding.UTF8.GetBytes(buffer.ToString());
                    string ss = Encoding.Default.GetString(data);
                    using (Stream stream = request.GetRequestStream())
                    {
                        stream.Write(data, 0, data.Length);
                        stream.Close();
                    }
                }
                //获取服务端返回
                response = (HttpWebResponse)request.GetResponse();
                StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                result = sr.ReadToEnd().Trim();
                MJson json = new MJson();
                json.Message = result;
                json.status = response.StatusCode.ToString().ToUpper();
                sr.Close();
                return json;
            }
            catch (System.Threading.ThreadAbortException e)
            {
                LogHelper.WriteLog("HttpService Thread - caught ThreadAbortException - resetting." + e.ToString());
                System.Threading.Thread.ResetAbort();
            }
            catch (WebException e)
            {
                var x = e.Response as HttpWebResponse;
                StreamReader sr = new StreamReader(x.GetResponseStream(), Encoding.UTF8);
                result = sr.ReadToEnd().Trim();
                sr.Close();
                sr.Dispose();
                MJson message = JsonConvert.DeserializeObject<MJson>(result);
                message.status = x.StatusCode.ToString();
                return message;
                //LogHelper.WriteLog("HttpService Thread - caught ThreadAbortException - resetting." + e.ToString());
                //throw new Exception(e.ToString());
            }
            catch (Exception e)
            {
                LogHelper.WriteLog("HttpService", e);
                throw new Exception(e.ToString());
            }
            finally
            {
                //关闭连接和流
                if (response != null)
                {
                    response.Close();
                }
                if (request != null)
                {
                    request.Abort();
                }
            }
            return new MJson { Message = result };
        }


        /// <summary>
        /// 处理http GET请求，返回数据
        /// </summary>
        /// <param name="url">请求的url地址</param>
        /// <returns>http GET成功后返回的数据，失败抛WebException异常</returns>
        public static MJson Get(string url)
        {
            System.GC.Collect();
            string result = "";

            HttpWebRequest request = null;
            HttpWebResponse response = null;
            var client = new WebClient();

            //请求url以获取数据
            try
            {
                /***************************************************************
                * 下面设置HttpWebRequest的相关属性
                * ************************************************************/
                string allurl = ConfigurationManager.AppSettings["RequestURL"].ToString();
                ServicePointManager.DefaultConnectionLimit = 200;//http请求的并发连接数最大值设置
                request = (HttpWebRequest)WebRequest.Create(allurl + url);
                request.Method = "GET";
                //获取服务器返回
                //string statuscore =resp;
                response = (HttpWebResponse)request.GetResponse(); 
                StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                result = sr.ReadToEnd().Trim();
                MJson ss = new MJson();
                ss.Message = result;
                ss.status = response.StatusCode.ToString().ToUpper();
                sr.Close();
                sr.Dispose();
                return ss;
                //获取HTTP返回数据

                //client.Encoding = Encoding.UTF8;
                //var str = client.DownloadString(url);
                //return str;
            }
            catch (System.Threading.ThreadAbortException e)
            {
                LogHelper.WriteLog("HttpService Thread - caught ThreadAbortException - resetting." + e.ToString());
                System.Threading.Thread.ResetAbort();
            }
            catch (WebException e)
            {
                LogHelper.WriteLog("HttpService Thread - caught ThreadAbortException - resetting." + e.ToString());
                var x = e.Response as HttpWebResponse;
                StreamReader sr = new StreamReader(x.GetResponseStream(), Encoding.UTF8);
                result = sr.ReadToEnd().Trim();
                sr.Close();
                sr.Dispose();
                MJson message = JsonConvert.DeserializeObject<MJson>(result);
                message.status = x.StatusCode.ToString().ToUpper();
                return message;
                //LogHelper.WriteLog("HttpService Thread - caught ThreadAbortException - resetting."+e.ToString());
                //throw new Exception(e.ToString());
            }
            catch (Exception e)
            {
                LogHelper.WriteLog("HttpService", e);
                throw new Exception(e.ToString());
            }
            finally
            {
                //关闭连接和流
                if (response != null)
                {
                    response.Close();
                }
                if (request != null)
                {
                    request.Abort();
                }
            }
            return new MJson { Message=result };
        }
        public class MJson
        {
            public string Message { get; set; }
            public string status { get; set; }
        }
        /// <summary>
        /// 硬件信息缓存
        /// </summary>
        public static DeviceInfo deviceInfoModel { get; set; }
        /// <summary>
        /// 箱子信息
        /// </summary>
        public static List<DBoxList> dBoxLists { get; set; }
        /// <summary>
        /// 箱子价格
        /// </summary>
        public static List<CostDetail> costDetailList { get; set; }
        /// <summary>
        /// 存储情况
        /// </summary>
        public static List<StorageModel> storageList { get; set; }

        public static AllDeviceBoxDetail allDeviceBoxDetail { get; set; }


    }
}
